// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const $ = db.command.aggregate;
// 云函数入口函数
exports.main = async (event, context) => {
  let user_openid = cloud.getWXContext().OPENID;
  if (event.mold == 'my') {
    let dfh = await db.collection('ops_order').where({
      user_openid: user_openid,
      status: 1
    }).count();
    let yfh = await db.collection('ops_order').where({
      user_openid: user_openid,
      status: 2
    }).count();
    let ysh = await db.collection('ops_order').where({
      user_openid: user_openid,
      status: 3
    }).count();
    return [dfh, yfh, ysh];
  } else if (event.mold == 'wait') {
    return await db.collection('ops_order').aggregate().sort({
      update_time: -1
    }).match({
      user_openid: user_openid,
      status: 1
    }).lookup({
      from: 'ops_goods',
      localField: 'goods_id',
      foreignField: '_id',
      as: 'goodsList',
    }).replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$goodsList', 0]), '$$ROOT'])
    }).project({
      goodsList: 0
    }).end();
  } else if (event.mold == 'already') {
    return await db.collection('ops_order').aggregate().sort({
      update_time: -1
    }).match({
      user_openid: user_openid,
      status: 2
    }).lookup({
      from: 'ops_goods',
      localField: 'goods_id',
      foreignField: '_id',
      as: 'goodsList',
    }).replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$goodsList', 0]), '$$ROOT'])
    }).project({
      goodsList: 0
    }).end();
  }
}